<template>
  <div>
    <!-- 头部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 中心卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <div>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-input placeholder="请输入内容" v-model="searchText" clearable>
                <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
              </el-input>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
              <el-button type="primary" @click="addUser">添加用户</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
      <!-- table区域 -->
      <div class="content">
        <el-table :data="this.userList" style="width: 100%" :border="true" v-loading="loading">
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态">
            <template v-slot="slot">
              <el-switch v-model="slot.row.mg_state" @change="updateUserStatus(slot.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                @click="handleEdit(scope.row)"
                type="primary"
                size="mini"
                icon="el-icon-edit"
              ></el-button>
              <el-button
                @click="deleteUserById(scope.row)"
                type="danger"
                size="mini"
                icon="el-icon-delete"
              ></el-button>
              <el-tooltip
                class="item"
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <el-button type="warning" size="mini" icon="el-icon-setting" @click="assignRole(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页区域 -->
      <div class="pages">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="this.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="this.total"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 添加修改用户的弹框 -->
    <el-dialog :title="title" :visible.sync="addUpdataVisible">
      <!-- 添加修改用户的表单 -->
      <el-form
        :model="addUpdateForm"
        :rules="addUpdateRules"
        ref="addUpdateForm"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username" close="cancelSubmit">
          <el-input v-model="addUpdateForm.username" :disabled="updateId!=''"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="title === '添加用户' ? true : false">
          <el-input v-model="addUpdateForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUpdateForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addUpdateForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 弹框尾部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelSubmit">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色弹框 -->
    <el-dialog title="分配角色" :visible.sync="assignRoles">
      <p><b>当前用户:</b>{{this.username}}</p>
      <p><b>当前角色:</b>{{this.rolename}}</p>
      <p><b>分配的新角色:</b>
      <el-select v-model="roleValue" placeholder="请选择">
       <el-option
        v-for="item in roleList"
        :key="item.id"
        :label="item.roleName"
        :value="item.id">
      </el-option>
      </el-select>
      </p>
      <!-- 弹框尾部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignRoles = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import _ from "lodash";
import {
  reqUserList,
  reqUpdateStatus,
  reqAddUser,
  reqUpdateUser,
  reqDeleteUser,
  reqRoleList,
  reqUpdateRolePower
} from "../../api/index";
export default {
  data() {
    // 验证邮箱的规则
    var emailValidator = (rule, value, callback) => {
      const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      if (!regEmail.test(value)) {
        return callback(new Error("请输入合法的邮箱"));
      }
      callback();
    };
    // 验证手机号的规则
    var mobileValidator = (rule, value, callback) => {
      const regMobile = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
      if (!regMobile.test(value)) {
        return callback(new Error("请输入合法的手机号"));
      }
      callback();
    };

    return {
      // 显示 loading
      loading: false,
      // 搜索框的文本
      searchText: "",
      // 当前的页数
      pagenum: 1,
      // 当前页显示多少条
      pagesize: 2,
      // 总数
      total: 1,
      // 获取用户列表
      userList: [],
      // 弹框的title
      title: "",
      // 控制弹框显示或隐藏
      addUpdataVisible: false,
      // 修改/角色的id
      updateId: "",
      // 分配角色显示和隐藏
      assignRoles: false,
      // 分配角色的名称
      username:'',
      rolename:'',
      roleId:'',
      // 获取角色列表
      roleList:[],
      roleValue:'',

      // 表单的数据
      addUpdateForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 表单的校验规则
      addUpdateRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 15, message: "长度在 3 到 15 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 18, message: "长度在 6 到 18 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: emailValidator, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: mobileValidator, trigger: "blur" }
        ]
      }
    };
  },

  methods: {
    //   获取用户的列表
    async getUserList(queryInfo, pageNum, pageSize) {
      //   请求数据
      const result = await reqUserList(
        this.searchText,
        this.pagenum,
        this.pagesize
      );
      this.loading = true;
      //   接收响应
      if (result.meta.status === 200) {
        this.userList = result.data.users;
        this.total = result.data.total;
        this.pagenum = result.data.pagenum;
      } else {
        this.$message.error(result.meta.msg);
      }
      this.loading = false;
    },

    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.pagesize = newSize;
      this.getUserList();
    },
    // 监听点击 页码值 改变的事件
    handleCurrentChange(newNum) {
      this.pagenum = newNum;
      this.getUserList();
    },

    // 点击按钮 搜索
    handleSearch() {
      this.getUserList();
    },

    // 更新用户的状态
    updateUserStatus: _.debounce(async function(user) {
      const uId = user.id;
      const type = user.mg_state;
      const result = await reqUpdateStatus(uId, type);
      if (result.meta.status === 200) {
        this.$message.success("更新用户状态成功");
      } else {
        return this.$message.error(result.meta.msg);
      }
    }, 500),

    // 添加修改 表单的统一校验
    submitForm() {
      this.$refs.addUpdateForm.validate(async valid => {
        if (!valid) return false;
        const { username, password, email, mobile } = this.addUpdateForm;
        if (!this.updateId) {
          const result = await reqAddUser(username, password, email, mobile);
          console.log(result);
          if (result.meta.status === 201) {
            this.$message.success("用户添加成功");
            this.getUserList();
          } else {
            this.$message.error(result.meta.msg);
          }
        } else {
          const result = await reqUpdateUser(this.updateId, email, mobile);
          if (result.meta.status === 200) {
            this.$message.success("用户修改成功");
            this.getUserList();
          } else {
            this.$message.error(result.meta.msg);
          }
        }
        // 关闭弹框
        this.addUpdataVisible = false;
      });
    },

    // 重置表单
    cancelSubmit() {
      this.addUpdataVisible = false;
      this.$refs.addUpdateForm.resetFields();
    },

    // 添加用户
    addUser() {
      this.updateId = ""
      this.addUpdataVisible = true;
      this.title = "添加用户";
      this.addUpdateForm.username = ""
      this.addUpdateForm.email = ""
      this.addUpdateForm.mobile = ""
    },

    // 编辑用户
    handleEdit(userInfo) {
      this.addUpdataVisible = true
      this.title = "修改用户"
      this.addUpdateForm.username = userInfo.username
      this.addUpdateForm.email = userInfo.email
      this.addUpdateForm.mobile = userInfo.mobile
      this.updateId = userInfo.id
    },

    // 删除用户
    deleteUserById(userInfo) {
      this.$confirm(
        `此操作将永久删除 ${userInfo.username} 用户, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(async () => {
          const result = await reqDeleteUser(userInfo.id)
          if (result.meta.status === 200) {
            this.$message.success("用户删除成功")
          } else {
            this.$message.error(result.meta.msg)
          }
          // 重新获取列表数据
          this.getUserList()
        })
        .catch(() => {
          this.$message.info("已取消删除")
        });
    },

    // 分配用户
    assignRole(userInfo) {
      this.assignRoles = true
      this.username = userInfo.username
      this.rolename = userInfo.role_name
      this.roleId = userInfo.id
    },

    // 获取角色列表
    async getRoleList(){
      const result = await reqRoleList()
      if(result.meta.status === 200){
        this.roleList = result.data
      }else{
        this.$message.error(result.meta.msg)
      }
    },

    // 保存角色
    async saveRole(){
      if(!this.roleValue) return false
      const result = await reqUpdateRolePower(this.roleId,this.roleValue)
      console.log(result)
      if(result.meta.status === 200){
        this.$message.success('更新角色成功')
        this.getUserList()
      }else{
        this.$message.error(result.meta.msg)
      }
      this.assignRoles = false
    }

  },

  created() {
    this.getUserList()
    this.getRoleList()
    console.log(this.updateId)
  }
};
</script>
<style lang="less" scoped>
.el-card {
  margin-top: 20px;

  .content {
    margin-top: 30px;
  }

  .pages {
    margin-top: 15px;
  }
}
.el-dialog{
    p{
      margin: 15px;
      b{
        margin-right: 15px;
      }
    }
  }
</style>

/**
======================43==================
用户的页面的基础显示
1. 头部面包屑

 */
